package com.example.neteaseapplication.util;

/*
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
*/

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class GetHtmlUtil {

    public static void lianjie() throws Exception {
        BufferedReader br = null;
        String charSet;
        URL url = new URL("https://music.163.com/#/search/m/?s=木偶人&type=1");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.connect();
        conn.setRequestProperty("user-agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/61.0.3163.79 Chrome/61.0.3163.79 Safari/537.36");
        conn.setRequestProperty("accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        int responsecode=conn.getResponseCode();
        String contenttype = conn.getContentType();

        charSet = getCharset(contenttype);
        if(responsecode == 200){

            InputStreamReader isr = new InputStreamReader(
                    conn.getInputStream(), charSet);
            br = new BufferedReader(isr);
        }
        String line;
        String mailreg = "<a(?:\\s+.)*?\\s+href=\"([^\"]*?)\"";

        Pattern p = Pattern.compile(mailreg);
        while ((line = br.readLine()) != null) {
            Matcher m = p.matcher(line);
            while (m.find()) {
                System.out.println(m.group());
            }
        }
        /*WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED);
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        String str1 = "https://music.163.com/#/search/m/?s=木偶人-薛之谦&type=1";
        HtmlPage htmlPage = webClient.getPage(str1);
        Thread.sleep(5000);

        String text=htmlPage.asText();


        System.out.println(text);*/
    }

    private static String getCharset(String str) {
        Pattern pattern = Pattern.compile("charset=.*");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find())
            return matcher.group(0).split("charset=")[1];
        return null;
    }
}
